package commonInfrastructure.accountManagement.managedbean;

import commonInfrastructure.accountManagement.entity.EmployeeEntity;
import commonInfrastructure.accountManagement.session.EmployeeSessionBean;
import commonInfrastructure.accountManagement.session.PasswordHashSessionBean;
import frm.billingAndPaymentProcessing.session.EJBTimerSessionLocal;
import java.io.IOException;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@ManagedBean
@RequestScoped
public class LoginManagementManagedBean {

    @EJB
    EmployeeSessionBean employeeManager;
    @EJB
    PasswordHashSessionBean passwordHashSessionBean;
    @EJB
    EJBTimerSessionLocal eJBTimerSessionLocal;
    private String userName;
    private String password;
    private Long loginUserId;

//private String message;
    public LoginManagementManagedBean() {
        userName = "";
        password = "";
        loginUserId = null;
    }

    public LoginManagementManagedBean(EmployeeSessionBean employeeManager) {
        this.employeeManager = employeeManager;
    }

    public void doLogin(ActionEvent event) throws IOException {

        HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
        HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
        //HttpSession session = request.getSession(true);
        try {
            EmployeeEntity systemUser = employeeManager.getEmployeeByUserName(getUserName());



            setPassword(passwordHashSessionBean.hashPassword(userName + getPassword()));
            if (systemUser.getPassword().equals(getPassword())) {
                String previousPage = "";
                //initialize the previousPage, avoid NullPointerException
                if (request.getSession().getAttribute("lastAction") == null) {
                    previousPage = "/index.xhtml";
                } else {
                    previousPage = request.getSession().getAttribute("lastAction").toString();
                }

                request.getSession().setAttribute("isLogin", true);

                Long systemUserId = systemUser.getId();
                request.getSession().setAttribute("userId", systemUserId);

                // if(previousPage.endsWith("/")|| previousPage.endsWith("index.xhtml")){
                //FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Login Success, Your UserID is: "+ systemUserId, ""));

                //}
                //else{

                if (employeeManager.getEmployeeById(systemUserId).isFirstTimeLogin() == true) { //first time log in

                    FacesContext.getCurrentInstance().getExternalContext().getFlash().put("employeeFirstTimeLogin", systemUser);
                    FacesContext.getCurrentInstance().getExternalContext().redirect("/MerlionFoodERP-war/commonInfrastructure/firstTimeLoginPwdChange.xhtml");
                    //return;
                } else {//not first time login
                    FacesContext.getCurrentInstance().getExternalContext().getFlash().put("systemUserId", systemUserId);
                    FacesContext.getCurrentInstance().getExternalContext().redirect("/MerlionFoodERP-war" + previousPage);

                    //}
                    setLoginUserId(systemUser.getId());
                }
            } else {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Invalid Password.", ""));
                //setMessage("login Fail");

            }

        }catch(Exception e){
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Invalid UserName", ""));
            return;
        }
    }

    public void goLogin() throws IOException {
        FacesContext.getCurrentInstance().getExternalContext().redirect("./commonInfrastructure/login.xhtml");
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Long getLoginUserId() {
        return loginUserId;
    }

    public void setLoginUserId(Long loginUserId) {
        this.loginUserId = loginUserId;
    }
}
